package com.itheima.youdianda.interceptor;

import com.itheima.youdianda.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 * @author 袁鹏
 * @date 2022-09-06-20:19
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("接收请求: " + request.getRequestURI());
        String token = request.getHeader("x-token");
        //if(token == null || !JwtUtils.verifyToken(token)){
        //    response.sendRedirect("/dist/#/login");
        //    System.out.println("重定向到登录页面");
        //    return false;
        //}else{
        //    request.getSession().setAttribute("userId", JwtUtils.getClaims(token).get("id"));
        //    System.out.println("放行");
        //    return true;
        //}
        if(token != null) {
            String id = JwtUtils.getClaims(token).get("id").toString();
            request.getSession().setAttribute("userId", id);
        }
        return true;
    }
}
